/* Quiz Manager - Create and edit web quizzes.
 * Copyright (C) 2008  Alexis Brunet, Jean-Michel Brunet, Enrique Hotes, Carlo Russo
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package soen343.domain;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.dsrg.ts.threadLocal.DbRegistry;

import soen343.data.QuestionTDG;
import soen343.data.QuizTDG;

public class QuizMapper {
	private QuizMapper() {}

	public static Quiz findById(int id) {
		Quiz quiz = null;
		
		try {
			ResultSet rs = QuizTDG.findById(id);
			rs.first();
			String name = rs.getString("name"); 
			
			quiz = new Quiz(name, id);
			ResultSet questionRS = QuestionTDG.findByQuizId(id);
			
			while(questionRS.next()) {
				Question question = QuestionMapper.findById(questionRS.getInt("id"));
				if(question != null) {
					quiz.addQuestion(question);
				}
			}
		} catch (SQLException e) { }
		
		return quiz;
	}
	
	public static Quiz findByName(String name) {
		Quiz quiz = null;
	
		try {
			ResultSet rs = QuizTDG.findByName(name);
			rs.first();
			int id = rs.getInt("id");
			
			quiz = new Quiz(name, id);
			ResultSet questionRS = QuestionTDG.findByQuizId(id);
			
			while(questionRS.next()) {
				Question question = QuestionMapper.findById(questionRS.getInt("id"));
				if(question != null) {
					quiz.addQuestion(question);
				}
			}
		} catch (SQLException e) {}
					
		return quiz;
	}
	
	public static void closeConnection() throws SQLException {
		DbRegistry.closeDbConnection();
	}

	public static void insert(Quiz newQuiz) {
		try {
			QuizTDG.insert(newQuiz.getName());
		} catch (SQLException e) {

		}
	}
	
	public static void delete( Quiz quiz ){
		try {
			QuizTDG.delete(quiz.getId());
		} catch (SQLException e) {
		}
	}

	public static List<IQuiz> findAllQuizStubs() {
		List<IQuiz> quizList = new ArrayList<IQuiz>();
		try {
			ResultSet rs = QuizTDG.findAll();
			while(rs.next()) {
				quizList.add( 
					new QuizStub( new Quiz(
							rs.getString("name"), 
							rs.getInt("id")) 
						) );
			}
		} catch (SQLException e) { }
		return quizList;
	}
}
